package com.app.socketserver;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * Created Date 2019/5/20
 *
 * @author liangkun
 * description：
 */
public class MyService extends Service {
    private ServerSocket serverSocket;

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        super.onCreate();
        startServer();
    }

    private void startServer() {

        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    serverSocket = new ServerSocket(8888);
                    DebugLog.d("SOCKET-PP " + "服务端已启动，等待客户端连接..");
                    while (true) {
                        if (!serverSocket.isClosed()) {
                            Socket socket = serverSocket.accept();// 侦听并接受到此套接字的连接,返回一个Socket对象
                            SocketServerThread socketThread = new SocketServerThread(socket);
                            socketThread.start();
                        }
                    }
                } catch (IOException e) {
                    DebugLog.d("SOCKET-PP " + "------------------- ：");
                    e.printStackTrace();
                    try {
                        if (serverSocket != null) {
                            serverSocket.close();
                            serverSocket = null;
                        }

                    } catch (IOException e1) {
                        e.printStackTrace();
                    }

                }
            }
        }).start();

    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        try {
            if (serverSocket != null) {
                serverSocket.close();
                serverSocket = null;
            }

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
//
//    @Override
//    protected void onDestroy() {
//        super.onDestroy();
//        try {
//            if (serverSocket != null) {
//                serverSocket.close();
//                serverSocket = null;
//            }
//
//        } catch (IOException e) {
//            e.printStackTrace();
//        }
//    }
//}
